<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class ApiAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {  //获取到用户数据，并赋值给$user

                return response() -> json([
                    'code' => '401',
                    'error_code' => '1004',
                    'message' => '无此用户',
                ]);
            }
            return $next($request);

        } catch (TokenExpiredException $e) {
            try {
                $token = auth() -> refresh();
                return $this->setAuthenticationHeader($next($request), $token);
            } catch (JWTException $e) {
                return response() -> json([
                    'code' => '401',
                    'error_code' => '1003',
                    'message' => 'token 过期，重新登录'
                ]);
            }

        }  catch (TokenInvalidException $e) {

            return response() -> json([
                'code' => '401',
                'error_code' => '1002',
                'message' => 'token 无效',
            ]);
        } catch (JWTException $e) {

            return response() -> json([
                'code' => '401',
                'error_code' => '1001',
                'message' => '缺少token',
            ]);
        }

    }

    protected function setAuthenticationHeader($response, $token = null)
    {
        $token = $token ?: auth() -> refresh();
        $response->headers->set('Authorization', 'Bearer '.$token);
        $response->headers->set('Access-Control-Expose-Headers', 'Authorization');

        return $response;
    }

}
